package com.filldream.fastboot.core.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.filldream.fastboot.base.mapper.HolidayMapper;
import com.filldream.fastboot.common.entity.R;
import com.filldream.fastboot.common.entity.db.HolidayDTO;
import com.filldream.fastboot.common.util.Assert;
import com.filldream.fastboot.common.util.HolidayUtil;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Component
public class HolidayManager {

    @Resource
    private HolidayMapper holidayMapper;

    private static HolidayManager self;

    @PostConstruct
    void init() {
        self = this;
        self.holidayMapper = this.holidayMapper;
    }

    public static R<List<HolidayDTO>> appendHoliday(Integer year) {
        List<HolidayDTO> list = HolidayUtil.holidayByYear(year + "");
        return appendHoliday(list);
    }

    public static R<List<HolidayDTO>> appendHoliday(String apiResultJson) {
        Assert.checkBoolean( JSONUtil.isJson(apiResultJson),"同步节假日失败，数据不对" );
        List<HolidayDTO> list = HolidayUtil.analysisJson(apiResultJson);
        return appendHoliday(list);
    }

    public static R<List<HolidayDTO>> appendHoliday(List<HolidayDTO> list) {
        for (HolidayDTO item : list) {
            String date = item.getDate();
            Long repeatCount = self.holidayMapper.selectCount(new LambdaQueryWrapper<HolidayDTO>().eq(HolidayDTO::getDate, date));
            if( repeatCount <= 0 ){
                self.holidayMapper.insert(item);
            }
        }
        return R.autoSuccess(list);
    }

    public static List<HolidayDTO> getListByYear(Integer year) {
        return self.holidayMapper.selectList(new LambdaQueryWrapper<HolidayDTO>().like(HolidayDTO::getDate, year+""));
    }

    public static Boolean nowIsHoliday(){
        String date = DateUtil.formatDate(new Date());
        List<HolidayDTO> holidayList = getListByYear(DateUtil.thisYear());
        HolidayDTO holidayDTO = holidayList.stream().filter(t -> t.getDate().equals(date)).findFirst().orElse(null);
        return holidayDTO == null ? false : holidayDTO.getHoliday();
    }

}
